<template>
  <div class="main">
    <el-header>
      <div class="header-leftbox">
        <img :src="avaterImg" alt="" />
        <span>我的购物车</span>
      </div>
      <div class="header-right">
        <el-button type="info" @click="logout">返回首页</el-button>
      </div>
    </el-header>
    <div class="cartMain">
      <div class="main-box">
        <div class="empty" v-if="isEmpty">
          <el-empty description="你的购物车还没有商品快去商场添加哦！" />
          <el-link @click="toShop">去商城</el-link>
        </div>
        <div class="cartBoxTitle" v-if="!isEmpty">
          <div class="search-box">
            <div class="search">
              <el-input v-model="input" placeholder="">
                <template #append>
                  <el-button :icon="Search" />
                </template>
              </el-input>
            </div>
          </div>
          <div class="Area">
            <h3>全部商品 {{ cartGoodsNum }}</h3>
            <div class="sendA">
              <span>配送至:</span>
              <div>
                <span>{{ LocationCity }}</span>
              </div>
            </div>
          </div>
          <div class="tableTop">
            <div class="cl cl1">
              <el-checkbox
                v-model="checkedAll"
                label="全选"
                size="large"
                @change="allChose"
              />
            </div>
            <div class="cl cl2">
              <span>商品</span>
            </div>
            <div class="cl cl3">
              <span>单价</span>
            </div>
            <div class="cl cl4">
              <span>数量</span>
            </div>
            <div class="cl cl5">
              <span>小计</span>
            </div>
            <div class="cl cl6">
              <span>操作</span>
            </div>
          </div>
          <div class="tableMainBox">
            <div class="shopList" v-for="item in cartList" :key="item">
              <div class="item">
                <div class="item-list">
                  <div class="check-box cl7">
                    <el-checkbox
                      v-model="item.checked"
                      size="large"
                      @change="handleChange(item)"
                    />
                  </div>
                  <div class="goodDetail">
                    <div class="imgBox">
                      <img :src="item.defaultImage" alt="" />
                    </div>
                    <div class="intrduce">
                      <span>{{ item.displayName }}</span>
                    </div>
                    <div class="attrbute">
                      <span>{{ item.skuName }}</span>
                    </div>
                  </div>
                  <div class="price">
                    <span>¥ {{ item.price }}.00</span>
                  </div>
                  <div class="number">
                    <el-input-number
                      v-model="item.quantity"
                      :min="1"
                      :max="100"
                      size="small"
                      @change="numHandleChange(item)"
                    />
                  </div>
                  <div class="num">¥ {{ item.price * item.quantity }}.00</div>
                  <div class="opreration">
                    <el-button type="primary" @click="dropItem(item.serialNo)"
                      >删除</el-button
                    >
                    <el-button
                      type="primary"
                      @click="removeToMyFavorite(item.spuNo)"
                      >移入关注</el-button
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="cartBoxBottom" v-if="!isEmpty">
            <div class="leftBox">
              <el-checkbox
                v-model="checkedAll"
                label="全选"
                size="large"
                @change="allChose"
              />
              <span class="spanStyle" @click="dropChoseGood"
                >删除选中的商品</span
              >
              <div class="clearCart" @click="clearCart">清理购物车</div>
            </div>
            <div class="rightBox">
              <span
                >已选择
                <p>&nbsp;{{ choseListNum }}&nbsp;</p>
                件商品</span
              >
              <div class="priceSum">
                总价:<span>¥{{ totlePrice }}</span>
              </div>
              <el-button @click="pageToPay">去结算</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <footer-view></footer-view>
  </div>
</template>

<script>
import AMap from "AMap";
import { Search } from "@element-plus/icons-vue";
import avaterImg from "../../assets/image/avaterDemo.jpg";
import { cartInfoList, removeCartInfo, saveCollectionInfo } from "@/api/user";
export default {
  data() {
    return {
      loading: true,
      LocationCity: "正在定位",
      selectedOptions: [],
      cartList: [],
      activeIndex: "1",
      choseListNum: 0,
      totlePrice: 0,
      checkedAll: false,
      choseAddress: "上海市",
      avaterImg: avaterImg,
      cartChoseList: [],
    };
  },
  computed: {
    isEmpty() {
      if (this.cartList.length > 0) {
        return false;
      }
      return true;
    },
    cartGoodsNum() {
      return this.$store.getters.cartLengthStatictic;
    },
  },
  mounted() {
    this.getCartInfoList();
    this.init();
    this.getLocation();
  },
  setup() {
    return {
      Search,
    };
  },
  updated() {},
  methods: {
    // 返回主页
    logout() {
      window.sessionStorage.clear();
      this.$router.push("/home");
    },
    // 去商场
    toShop() {
      this.$router.push("/shop");
    },
    numHandleChange(item) {
      this.cartList.goodsTotil =
        this.cartList.goodPrice * this.cartList.goodsNum;
      this.computeChoseGood();
    },
    // 购物车商品数量变化时，金额的变换
    handleChange(event) {
      this.cartList.goodsTotil =
        this.cartList.goodPrice * this.cartList.goodsNum;
      this.computeChoseGood();
    },
    // 挂载时初始化数据函数
    init() {
      let userInfo = this.$store.getters.getUserInfo;
      console.log(userInfo);
      if (userInfo.avatar) {
        this.avaterImg = userInfo.avatar;
      }
    },
    // 全选事件
    allChose() {
      if (this.checkedAll == false) {
        this.cartList.forEach((item) => {
          item.checked = false;
        });
      } else if (this.checkedAll == true) {
        this.cartList.forEach((item) => {
          item.checked = true;
        });
      }
      this.computeChoseGood();
    },
    // 选中几个物品个数统计以及总数
    computeChoseGood() {
      let num = 0;
      let priceNum = 0;
      this.cartList.forEach((item) => {
        if (item.checked == true) {
          num++;
          priceNum += item.price * item.quantity;
        }
        this.choseListNum = num;
        this.totlePrice = priceNum;
      });
    },
    // 单个购物车选中
    listItemCheck(event) {
      this.computeChoseGood();
    },
    // 删除购物车的某一项
    dropItem(serialNo) {
      let msg = "你确定要将该物品移除购物车吗?";
      // 弹出一个框，用来提示用户是否确定删除
      this.$confirm(msg, "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      })
        .then(() => {
          removeCartInfo([serialNo]).then((res) => {
            if (res.code === 0) {
              this.$message.success("删除成功");
              this.getCartInfoList();
            }
          });
        })
        .catch(() => {
          console.log("cancel");
        });
    },
    // 删除选中的购物车内容
    dropChoseGood() {
      let msg = "你确定要删除选中项吗?";
      // 弹出一个框，用来提示用户是否确定删除
      this.$confirm(msg, "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      })
        .then(() => {
          let num = this.computerTrueNum();
          let serialNos = [];
          let length = this.cartList.length;
          if (num != length) {
            this.cartList.forEach((item, index) => {
              if (item.checked == true) {
                serialNos.push(item.serialNo);
                removeCartInfo(serialNos).then((res) => {
                  console.log(res);
                  if (res.code === 0) {
                    this.$message.success("删除成功");
                    window.location.reload();
                  }
                });
              }
            });
          } else {
            this.clearCart();
          }
        })
        .catch(() => {
          console.log("cancel");
        });
    },
    // 清空购物车
    clearCart() {
      let serialNos = [];
      let msg = "你确定要清空购物车吗?";
      // 弹出一个框，用来提示用户是否确定删除
      this.$confirm(msg, "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      })
        .then(() => {
          this.cartList.forEach((item, index) => {
            serialNos.push(item.serialNo);
            removeCartInfo(serialNos).then((res) => {
              console.log(res);
              if (res.code === 0) {
                this.$message.success("删除成功");
                window.location.reload();
              }
            });
          });
        })
        .catch(() => {
          console.log("cancel");
        });
    },
    // 计算数组中为选中的个数
    computerTrueNum() {
      let num = 0;
      this.cartList.forEach((item) => {
        if (item.checked == true) {
          num++;
        }
      });
      return num;
    },
    // 移入我的关注
    removeToMyFavorite(spuNo) {
      let favoItem = {
        objectType: "goods",
        objectNo: spuNo,
        toppingFlag: "N",
      };
      saveCollectionInfo(favoItem).then((res) => {
        console.log(res);
        if (res.code === 0) {
          this.$message.success("成功添加到我的收藏");
        }
      });
    },
    // 获取定位
    getLocation() {
      const _this = this;
      AMap.plugin("AMap.CitySearch", function () {
        var citySearch = new AMap.CitySearch();
        citySearch.getLocalCity(function (status, result) {
          console.log(result);
          if (status === "complete" && result.info === "OK") {
            // 查询成功，result即为当前所在城市信息
            console.log("通过ip获取当前城市：", result);
            _this.LocationCity = result.city;
          } else {
            console.log("error");
          }
        });
      });
    },
    // 去结算页面
    pageToPay() {
      let num = this.computerTrueNum();
      if (num == 0) {
        this.$message.error("请至少选择一个商品");
        return;
      }
      let chose = [];
      this.cartList.forEach((item, index) => {
        if (item.checked === true) {
          chose.push(this.cartList[index]);
        }
      });
      this.cartChoseList = chose;
      console.log(this.cartChoseList);
      sessionStorage.setItem("choseList", JSON.stringify(this.cartChoseList));
      sessionStorage.setItem("totlePrice", this.totlePrice);
      this.$router.push("/payOrder");
    },
    // 获取购物车列表
    getCartInfoList() {
      cartInfoList().then((res) => {
        console.log(res);
        if (res.code === 0) {
          this.cartList = res.page.list;
          this.cart;
        }
      });
    },
  },
};
</script>

<style lang="scss">
.main {
  background-color: #fff;
  .el-header {
    background-color: #f6fbf6;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 70px;
    .header-leftbox {
      display: flex;
      align-items: center;
      img {
        height: 30px;
        width: 30px;
        margin: 0 20px;
        border-radius: 50%;
        border: 1px solid #244d4d;
        box-shadow: 1px 1px #ededf1;
      }
      span {
        color: #244d4d;
        font-size: 30px;
        font-weight: bold;
      }
    }
    .header-right {
      display: flex;
      align-items: center;
      .el-button {
        font-weight: bold;
        background-color: #244d4d;
      }
    }
  }
  .cartMain {
    display: flex;
    justify-content: center;
    .main-box {
      display: flex;
      width: 1000px;
      min-height: 500px;
      flex-direction: column;
      .empty {
        display: flex;
        flex-direction: column;
        justify-content: center;
      }
      .cartBoxTitle {
        padding: 10px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .search-box {
          width: 1000px;
          justify-content: flex-end;
          display: flex;
          margin: 20px 0;
          .search {
            .el-input .el-input__wrapper {
              border-radius: 0;
              width: 200px;
              height: 30px;
              border: 1px solid #244d4d;
            }
            .el-button {
              background-color: #244d4d;
              color: #fff;
              height: 30px;
              border-radius: 0;
            }
          }
        }
        .Area {
          position: relative;
          margin: 20px 0;
          width: 1000px;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: space-between;
          h3 {
            font-weight: 700;
            font-size: 16px;
          }
          .sendA {
            display: flex;
            align-items: center;
          }
          span {
            color: #434343;
            font-size: 14px;
            margin: 0 5px;
          }
          .areaChose {
            border: 1px solid #cecece;
            display: flex;
            font-size: 14px;
            color: #434343;
            background-color: #fff;
            height: 24px;
            align-items: center;
            justify-content: flex-start;
            padding: 0 10px;
            overflow: hidden;
            &:hover {
              cursor: pointer;
              border-bottom: 0;
              .textArea {
                display: block;
              }
            }
          }
        }
        .tableTop {
          width: 1000px;
          display: block;
          height: 32px;
          line-height: 32px;
          margin: 0 0 10px;
          padding: 5px 10px;
          background: #f3f3f3;
          border: 1px solid #e9e9e9;
          border-top: 0;
          position: relative;
          display: flex;
          align-items: center;
          .cl {
            font-size: 14px;
            color: #434343;
          }
        }
        .tableMainBox {
          display: flex;
          justify-content: flex-start;
          flex-direction: column;
          width: 1000px;
          min-height: 500px;
          .shop {
            width: 100%;
            display: flex;
            align-items: center;
            color: #666;
            font-size: 14px;
            padding: 5px 10px;
            .shop-name {
              margin: 0 10px;
            }
          }
          .item {
            border: 1px solid #e9e9e9;
            margin-top: 10px;
            min-height: 200px;
            .item-list {
              border-top: 2px solid #aaa;
              display: flex;
              color: #333;
              align-items: center;
              font-size: 14px;
              padding: 20px 10px;
              .goodDetail {
                width: 480px;
                padding: 5px;
                display: flex;
                align-items: center;
                font-size: 14px;
                color: #333;
                .imgBox {
                  border: 1px solid #e9e9e9;
                  height: 80px;
                  width: 80px;
                  margin: 0 10px;
                  img {
                    height: 100%;
                    width: 100%;
                  }
                }
                .intrduce {
                  width: 300px;
                  font-size: 16px;
                  font-weight: 700;
                  margin: 0 5px;
                }
                .attrbute {
                  width: 100px;
                  font-size: 12px;
                  font-weight: 600;
                  margin: 0 20px;
                }
              }
              .price {
                padding: 5px 0 0 10px;
                width: 100px;
                font-weight: 700;
              }
              .number {
                padding: 5px 0 0 20px;
                width: 200px;
                text-align: center;
              }
              .num {
                padding: 5px 0 0 30px;
                width: 120px;
                font-weight: 700;
              }
              .opreration {
                padding: 0 0 0 20px;
                width: 100px;
                .el-button {
                  width: 80px;
                  background-color: #244d4d;
                  border: 0;
                  border-radius: 0;
                  color: #fff;
                  margin: 10px 0;
                }
              }
            }
          }
        }
        .cartBoxBottom {
          overflow: hidden;
          margin: 20px 0;
          width: 1000px;
          border: 1px solid #e9e9e9;
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 50px;
          padding: 0 0 0 5px;
          .leftBox {
            display: flex;
            align-items: center;
            color: #666;
            font-size: 14px;
            .spanStyle {
              margin: 0 5px;
              &:hover {
                cursor: pointer;
                color: #244d4d;
                font-weight: 700;
              }
            }
            .clearCart {
              color: #244d4d;
              font-weight: bold;
              &:hover {
                cursor: pointer;
                transform: scale(1.1);
              }
            }
          }
          .rightBox {
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #999;
            span {
              margin: 0 5px;
              display: flex;
              p {
                color: #244d4d;
                font-weight: bold;
              }
            }
            .priceSum {
              margin: 0 5px 0 10px;
              display: flex;
              align-items: center;
              span {
                color: #244d4d;
                font-weight: bold;
                font-size: 18px;
              }
            }
            .el-button {
              border-radius: 0;
              border: 0;
              background-color: #244d4d;
              color: #ffff;
              height: 50px;
              font-weight: bold;
              &:hover {
              }
            }
          }
        }
      }
    }
  }
}
// 公共部分样式
.cl1 {
  width: 133px;
}
.cl2 {
  width: 400px;
}
.cl3 {
  width: 170px;
}
.cl4 {
  width: 80px;
}
.cl5 {
  width: 140px;
  text-align: right;
  padding-right: 50px;
}
.cl6 {
  width: 75px;
  padding-left: 25px;
}
.cl7 {
  width: 30px;
}
</style>
